import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:get/get_state_manager/src/rx_flutter/rx_obx_widget.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/public/consts.dart';
import '../../../components/XDialogs/dialog_utils.dart';
import '../../../components/XDialogs/LoadingDialog.dart';
import '../../../components/BeautifulBGWidget/BeautifulBGWidget.dart';
import '../../../components/Tip/ToastUtils.dart';
import '../../../components/XTextField/XTextField.dart';
import '../../../config/location.dart';
import '../../../dart/base/model.dart';
import '../../../main.dart';
import '../components/ClauseWidget/ClauseWidget.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<RegisterPage> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  TextEditingController userNameController = TextEditingController();
  TextEditingController passWordController = TextEditingController();
  TextEditingController verifyPassWordController = TextEditingController();

  TextEditingController phoneNumberController = TextEditingController();
  TextEditingController dynamicCodeController = TextEditingController();
  TextEditingController nickNameController = TextEditingController();
  TextEditingController realNameController = TextEditingController();
  TextEditingController remarkController = TextEditingController();

  var agreeRegTerms = false;

  var passwordUnVisible = true;

  var verifyPassWordUnVisible = true;

  //右滑返回
  double distance = 0;

  //是够允许点击登录
  var allowCommit = false;

  var sendVerify = false;

  var dynamicId = '';
  //验证码重置时间
  var countDown = 60;
  //开始计时
  var startCountDown = false;

  Timer? timer;

  final IResources resources = getResouces();
  // 验证码动态密码ID
  late String _dynamicId = "";

  @override
  void initState() {
    // agreeRegTerms = Storage.getBool('agreeTerms');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BeautifulBGWidget(
        showBack: true,
        showLogo: false,
        body: Padding(
            padding: const EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [buildTitle(), registerForm()],
            )));
  }

  Widget buildTitle() {
    return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
      Text(
        '注册奥集能账户',
        style: TextStyle(fontSize: 28, fontWeight: FontWeight.w600),
      ),
      const SizedBox(
        height: 8,
      ),
      Text(
        '请完善个人信息',
        style: TextStyle(fontSize: 14, fontWeight: FontWeight.w400, color: Colors.grey),
      ),
      const SizedBox(
        height: 20,
      )
    ]);
  }

  Widget tips() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '欢迎使用奥集能',
          style: TextStyle(fontSize: 40.sp),
        ),
        Text(
          '请完善个人信息',
          style: TextStyle(
            fontSize: 20.sp,
            color: Colors.grey.shade400,
          ),
        ),
      ],
    );
  }

  Widget stepOne() {
    return Column(
      children: [
        XTextField.input(
            controller: userNameController, hint: "请输入用户名", title: "用户名"),
        XTextField.input(
            controller: passWordController,
            hint: "请输入密码",
            title: "密码",
            obscureText: passwordUnVisible,
            action: IconButton(
                onPressed: () {
                  showPassWord();
                },
                icon: Icon(
                  passwordUnVisible ? Icons.visibility_off : Icons.visibility,
                  size: 24.w,
                  color: Colors.grey,
                ))),
        XTextField.input(
            controller: verifyPassWordController,
            hint: "请再次输入密码",
            title: "确认密码",
            obscureText: verifyPassWordUnVisible,
            action: IconButton(
                onPressed: () {
                  showVerifyPassWord();
                },
                icon: Icon(
                  verifyPassWordUnVisible
                      ? Icons.visibility_off
                      : Icons.visibility,
                  size: 24.w,
                  color: Colors.grey,
                ))),
      ],
    );
  }

  // 计时的按钮
  Widget commonLimitedTimeButtonWidget({
    String name = "发送验证码",
    int countdown = 120,
    bool Function()? check,
    bool Function()? close,
    VoidCallback? click,
  }) {
    RxBool active = true.obs;
    RxString btnName = name.obs;
    startCountDown(int count) {
      Future.delayed(const Duration(milliseconds: 1000), () {
        if (count > 0) {
          active.value = false;
          btnName.value = '$name($count)';
          if (!(close?.call() ?? false)) {
            startCountDown(count - 1);
          }
        } else {
          btnName.value = name;
          active.value = true;
        }
      });
    }

    return Obx(() {
      return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          bool checkOk = check?.call() ?? true;
          if (active.value && checkOk) {
            click?.call();
            startCountDown(countdown);
          }
        },
        child: Container(
          padding: EdgeInsets.symmetric(vertical: 10.h, horizontal: 15.w),
          child: Text(
            btnName.value,
            style: TextStyle(
                color: active.value ? XColors.themeColor : Colors.grey.shade400,
                fontSize: 20.sp),
          ),
        ),
      );
    });
  }

  Widget registerWidget() {
    return Column(
      children: [
        XTextField.input(
            controller: phoneNumberController, hint: "请输入手机号", title: "手机号"),
        XTextField.input(
            controller: dynamicCodeController,
            hint: "请输入验证码",
            title: "验证码",
            action: commonLimitedTimeButtonWidget(
                check: checkPhoneNumber, click: getDynamicCode)),
        // XTextField.input(
        //   controller: nickNameController,
        //   hint: "请输入昵称",
        //   title: "昵称",
        // ),
        XTextField.input(
            controller: passWordController,
            hint: "请输入密码",
            title: "密码",
            obscureText: passwordUnVisible,
            action: IconButton(
                onPressed: () {
                  showPassWord();
                },
                icon: Icon(
                  passwordUnVisible ? Icons.visibility_off : Icons.visibility,
                  size: 24.w,
                  color: Colors.grey,
                ))),
        XTextField.input(
            controller: verifyPassWordController,
            hint: "请再次输入密码",
            title: "确认密码",
            obscureText: verifyPassWordUnVisible,
            action: IconButton(
                onPressed: () {
                  showVerifyPassWord();
                },
                icon: Icon(
                  verifyPassWordUnVisible
                      ? Icons.visibility_off
                      : Icons.visibility,
                  size: 24.w,
                  color: Colors.grey,
                ))),
        XTextField.input(
          controller: userNameController,
          hint: "请输入真实姓名",
          title: "姓名",
        ),
        XTextField.input(
          controller: remarkController,
          hint: "请输入座右铭",
          title: "座右铭",
        ),
      ],
    );
  }

  Widget loginButton() {
    return GestureDetector(
      onTap: () {
        register();
      },
      child: Column(
        children: [
          Container(
              width: double.infinity,
              height: 60.h,
              decoration: BoxDecoration(
                color: XColors.themeColor,
                borderRadius: BorderRadius.circular(40.w),
              ),
              alignment: Alignment.center,
              child: Text(
                "注册",
                style: TextStyle(color: Colors.white, fontSize: 20.sp),
              )),
        ],
      ),
    );
  }

  Widget registerForm() {
    return Column(
      children: [
        XTextField.input(
          controller: phoneNumberController,
          title: '手机号',
          hint: '请输入手机号',
        ),
        const SizedBox(height: 5),
        XTextField.input(
          controller: dynamicCodeController,
          title: '验证码',
          hint: '请输入验证码',
          action: Container(
            padding: const EdgeInsets.only(bottom: 5),
            child: verificationCodeCountDown(),
          ),
        ),
        const SizedBox(height: 5),
        XTextField.input(
          controller: passWordController,
          title: '密码',
          hint: '请输入密码',
          obscureText: passwordUnVisible,
          action: IconButton(
              padding: const EdgeInsets.only(left: 40),
              onPressed: () {
                showPassWord();
              },
              icon: Icon(
                passwordUnVisible ? Icons.visibility_off : Icons.visibility,
                size: 24.w,
                color: Colors.grey,
              )),
        ),
        const SizedBox(height: 5),
        XTextField.input(
          controller: verifyPassWordController,
          title: '确认密码',
          hint: '请再次输入密码',
          obscureText: verifyPassWordUnVisible,
          action: IconButton(
              padding: const EdgeInsets.only(left: 40),
              onPressed: () {
                showVerifyPassWord();
              },
              icon: Icon(
                verifyPassWordUnVisible
                    ? Icons.visibility_off
                    : Icons.visibility,
                size: 24.w,
                color: Colors.grey,
              )),
        ),
        const SizedBox(height: 5),
        XTextField.input(
          controller: realNameController,
          title: '姓名',
          hint: '请输入真实姓名',
        ),
        const SizedBox(height: 5),
        XTextField.input(
          controller: remarkController,
          title: '座右铭',
          hint: '请输入座右铭',
        ),
        const SizedBox(height: 20),
        ClauseWidget(
            isSelected: agreeRegTerms,
            changed: (v) {
              changeAgreeRegTerms();
            }),
        const SizedBox(height: 10),
        comfirmSubmit(),
      ],
    );
  }

  Widget comfirmSubmit() {
    return GestureDetector(
      onTap: () {
        register();
      },
      child: Container(
          width: 343,
          height: 45,
          // padding: const EdgeInsets.only(top: 12),
          decoration: ShapeDecoration(
            color: XColors.themeColor,
            shape: RoundedRectangleBorder(
              side: const BorderSide(width: 1, color: Color(0xFFE7E8EB)),
              borderRadius: BorderRadius.circular(8),
            ),
          ),
          child: const Center(
            child: Text(
              '注册',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white,
                fontSize: 16,
                fontFamily: 'PingFang SC',
                fontWeight: FontWeight.w600,
                // height: 0.01,
              ),
            ),
          )),
    );
  }

  Widget verificationCodeCountDown() {
    TextStyle textStyle = TextStyle(color: XColors.themeColor, fontSize: 20.sp);
    String text = '发送验证码';
    if (startCountDown) {
      textStyle = TextStyle(color: Colors.grey, fontSize: 15.sp);
      text = "$countDown秒后重新发送";
    }
    return GestureDetector(
        onTap: () {
          if (!sendVerify) {
            getDynamicCode();
          }
        },
        child: Text(
          text,
          textAlign: TextAlign.end,
          style: textStyle,
        ));
  }

  Widget backToLogin() {
    return Positioned(
        top: 60,
        left: 20,
        child: GestureDetector(
          onTap: (() {
            backToLoginPage();
          }),
          child: XIcons.arrowBack32,
        ));
  }

  void changeAgreeRegTerms() {
    agreeRegTerms = !agreeRegTerms;
    // Storage.setBool('agreeTerms', agreeRegTerms);
    setState(() {
    });
  }

  bool regExp(String regStr, String txt) {
    RegExp regExp = RegExp(regStr);
    Match? match = regExp.firstMatch(txt);

    return match == null;
  }

  bool validate() {
    if (!checkPhoneNumber()) {
      return false;
    }
    if (regExp(r'(\d{6})', dynamicCodeController.text)) {
      ToastUtils.showMsg(msg: '请输入正确的验证码');
      return false;
    }
    if (passWordController.text != verifyPassWordController.text) {
      ToastUtils.showMsg(msg: "输入的两次密码不一致！");
      return false;
    }
    if (passWordController.text.length < 6) {
      ToastUtils.showMsg(msg: "密码的长度不能小于6");
      return false;
    }
    if (passWordController.text.length > 15) {
      ToastUtils.showMsg(msg: "密码的长度不能大于15");
      return false;
    }
    if (regExp(Constants.passwordRegex, passWordController.text)) {
      ToastUtils.showMsg(msg: '密码必须包含：数字、字母、特殊字符');
      return false;
    }
    if (regExp(Constants.realNameRegex, realNameController.text)) {
      ToastUtils.showMsg(msg: "请输入正确的姓名：${realNameController.text}");
      return false;
    }
    if (remarkController.text.isEmpty) {
      ToastUtils.showMsg(msg: "请输入正确的座右铭");
      return false;
    }
    if (!agreeRegTerms) {
      ToastUtils.showMsg(msg: "请阅读并同意服务条款与隐私条款");
      return false;
    }

    return true;
  }

  bool checkPhoneNumber() {
    if (phoneNumberController.text.isEmpty) {
      ToastUtils.showMsg(msg: "请输入手机号");
      return false;
    } else if (regExp(Constants.accountRegex, phoneNumberController.text)) {
      ToastUtils.showMsg(msg: "请输入正确的手机号");
      return false;
    }

    return true;
  }

  // 获得动态验证码
  Future<void> getDynamicCode() async {
    RegExp regex = RegExp(Constants.accountRegex);
    if (!regex.hasMatch(phoneNumberController.text)) {
      ToastUtils.showMsg(msg: "请输入正确的手机号");
      return;
    }
    if (sendVerify) {
      ToastUtils.showMsg(msg: "验证码已发送，请稍后再试");
      return;
    }
    startCountDown = true;
    countDown = 60;
    _dynamicId = '';

    var res = await relationCtrl.auth.dynamicCode(DynamicCodeModel.fromJson({
      'account': phoneNumberController.text,
      'platName': resources.platName,
      'dynamicId': '',
    }));
    if (res.success && res.data != null) {
      _dynamicId = res.data!.dynamicId;
      sendVerify = true;
      startCountDownMethod();
    }
  }

  void startCountDownMethod() {
    if (timer != null) {
      if (timer!.isActive) {
        timerClose();
      }
    }
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countDown <= 0) {
        timerClose();
      }
      countDown--;
    });
    setState(() {});
  }

  void timerClose() {
    timer?.cancel();
    timer = null;
    startCountDown = false;
    countDown = 60;
    sendVerify = false;
  }

  // 注册
  void register() async {
    if (!validate()) return;

    LoadingDialog.showLoading(context);
    var res = await relationCtrl.auth.register(RegisterModel(
      account: phoneNumberController.text,
      dynamicId: _dynamicId,
      dynamicCode: dynamicCodeController.text,
      password: passWordController.text,
      name: realNameController.text,
      remark: remarkController.text,
    ));
    LoadingDialog.dismiss(context);
    if (res.success) {
      AlertDialogUtils.showPrivateKey(context, res.data?.privateKey ?? '');
    } else {
      ToastUtils.showMsg(msg: res.msg);
    }
    setState(() {});
  }

  void showPassWord() {
    passwordUnVisible = !passwordUnVisible;
    setState(() {});
  }

  void showVerifyPassWord() {
    verifyPassWordUnVisible = !verifyPassWordUnVisible;
    setState(() {});
  }

  void backToLoginPage() {
    Navigator.pop(context);
  }
}
